package com.darkteam.jhades.common;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.darkteam.jhades.common.message.RequestMessage;
import com.darkteam.jhades.cs.message.type.Head;

public class BaseServerDecoder extends FrameDecoder {

	private static final Logger logger = Logger
			.getLogger(BaseServerDecoder.class.getName());

	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {

		logger.log(Level.INFO, "decode: " + ChannelBuffers.hexDump(buffer));
		if (buffer.readableBytes() < 4) {
			return null;
		}
		byte head = buffer.readByte();
		if (!Head.isHead(head)) {
			buffer.readByte();// ignore
			head = buffer.readByte();// real head
		}

		if (head == Head.C1.getType() || head == Head.C3.getType()) {
			buffer.readByte();
		} else {
			buffer.readShort();
		}
		short function = buffer.readShort();

		if (function == (short) 0xA920) {
			buffer.readShort();
		}
		
		RequestMessage message = new RequestMessage(function);
		if(buffer.readable()){
			byte[] paran = new byte[buffer.readableBytes()];
			buffer.readBytes(paran);
			message.setParan(paran);
		}
		
		

		return message;
	}

	
}
